package com.wfh.aigenerator.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.wfh.aigenerator.ai.model.HtmlCodeResult;
import com.wfh.aigenerator.ai.model.MultiFileCodeResult;
import com.wfh.aigenerator.model.enums.CodeGenTypeEnums;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @Title: CodeFileSaver
 * @Author wangfenghuan
 * @Package com.wfh.aigenerator.core
 * @Date 2025/7/29 20:46
 * @description:
 */
public class CodeFileSaver {


    /**
     * 文件的根目录
     */
    public static final String FILE_SAVE_ROOT_DIR = System.getProperty("user.dir" + "/tmp/code_output/");

    /**
     * 保存html代码
     * @param htmlCodeResult
     * @return
     */
    public static File saveHtmlCodeResult(HtmlCodeResult htmlCodeResult) {
        String baseDirPath = buildFilePath(CodeGenTypeEnums.HTML.getValue());
        saveFile(baseDirPath, htmlCodeResult.getHtmlCode(), "index.html");
        return new File(baseDirPath);
    }

    /**
     * 保存多文件代码
     * @param multiFileCodeResult
     * @return
     */
    public static File saveMultiFileCodeResult(MultiFileCodeResult multiFileCodeResult) {
        String baseDirPath = buildFilePath(CodeGenTypeEnums.MULTI_FILE.getValue());
        saveFile(baseDirPath, multiFileCodeResult.getHtmlCode(), "index.html");
        saveFile(baseDirPath, multiFileCodeResult.getCssCode(), "style.css");
        saveFile(baseDirPath, multiFileCodeResult.getJsCode(), "script.js");
        return new File(baseDirPath);
    }
    /**
     * 构建唯一路径
     * @param bizType 代码类型
     * @return
     */
    private static String buildFilePath(String bizType) {
        String uniquePath = FILE_SAVE_ROOT_DIR + File.separator + bizType + "_" + IdUtil.getSnowflakeNextIdStr();
        String dirPath = FILE_SAVE_ROOT_DIR + File.separator + uniquePath;
        FileUtil.mkdir(dirPath);
        return dirPath;
    }

    /**
     * 保存单个文件
     * @param dirPath
     * @param fileContent
     * @param fileName
     */
    public static void saveFile(String dirPath, String fileContent, String fileName) {
        String filePath = dirPath + File.separator + fileName;
        FileUtil.writeString(fileContent, filePath, StandardCharsets.UTF_8);
    }

}
